import { defineStore } from 'pinia';
import { getRightData } from '@/api/earlyWarning';
import { getEffectivenessCode } from '@/enums/AlarmEffectivenessEnum';
import { getAlarmInfo } from '@/api/deviceAlarms';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import COMPONENT_TITLES from '@/constants/components/componentsTitle';
import { useDialogStore } from '@/store/modules/useDialogStore';

export interface IAlarmInfos {
  total: number;
  potencyAlarmNum: number;
  pressureAlarmNum: number;
  flowAlarmNum: number;
  normallyOpenAlarmNum: number;
  thirdAlarmNum: number;
  echartsData: IECharts[];
}

interface IECharts {
  id: string;
  name: string;
  value: number;
  itemStyle: {
    color: string;
  };

  [key: string]: any;
}

export const useDeviceAlarmsStore = defineStore('deviceAlarms', () => {
  const alarmInfos = ref(<IAlarmInfos>{});
  const { addPoint, clearAllPoints } = useCesiumPoints();
  const dataSource = reactive<Record<string, any[]>>({});
  const { flyTo } = useDialogStore();

  //点击饼图触发的事件
  const deviceAlarmsHandle = async (item: any) => {
    try {
      flyTo({ longitude: 117.140035075, latitude: 36.798747059 }, 400000);
      if (dataSource[item.name]) {
        clearAllPoints(dataSource[item.name]);
        delete dataSource[item.name];
      } else {
        const { data } = await getAlarmInfo({ effective: getEffectivenessCode(item.name) });
        dataSource[item.name] = data.map((point) => addPoint(point, item.name, COMPONENT_TITLES.DEVICE_ALARMS));
      }
    } catch (error) {
      console.log(error);
    }
  };
  const initClearPoints = () => {
    Object.keys(dataSource).forEach((key) => {
      clearAllPoints(dataSource[key]);
      delete dataSource[key];
    });
  };
  onMounted(async () => {
    const { data } = await getRightData({ type: 'alarmInfos' });
    alarmInfos.value = data.alarmInfos;
  });

  return {
    alarmInfos,
    deviceAlarmsHandle,
    initClearPoints
  };
});
